/**
 * @Description: 入口文件
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 31/07/24 6:04 PM
 */
import './public-path.ts'
import 'core-js/stable/url-search-params'
import 'core-js/stable/array' // polyfill
import 'core-js/stable/set-immediate' // polyfill
import 'core-js/stable/promise' // polyfill
import '@shared/utils/dom'
import { createApp, markRaw, watch } from 'vue'
// 后面考虑按需加载 TODO 低优化
import 'normalize.css'
import '@/style/' // 样式
import AppRoot from './App.vue' // 根组件
import store from '@store/index' // 状态管理
import router from './router/index.ts'
import { setup } from '@/setting.ts'
import useAppStore from '@store/use-app-store.ts'
import useUserStore from '@store/use-user-store.ts'
import useMenuStore from '@store/use-menu-store.ts'
import useLayoutStore from '@store/use-layout-store.ts'
import { enhanceRouter } from './router/use-router-plus.ts'
import baseSetup from '@shared/base/setup.ts' // 预览 需要获取全局的 app 实例
import DisableDevtool from 'disable-devtool'
import profile from '@root/profile.ts'
import { updateAppVersionPolling } from '@shared/utils/auto-update-client' // 询问是否自动更新
import plugins from './plugins' // plugins
import pkg from '@root/package.json'
import { dbSimple } from '@/utils/db.ts'
import directives from './directives/index.ts'

// sharedRepo
import * as dictObj from '@/utils/dict.ts'
;(window.$sharedRepo as any) ||= {
  ...dictObj
}

// types
import type { App as TApp } from 'vue'
import { QIANKUN_PLATFORM } from '@/utils/constants.ts'
import { deepClone, isPlainObject, to } from 'sf-utils2'

let app: TApp

function initApp(props?: any): TApp {
  app = createApp(AppRoot).use(baseSetup, window.$sharedRepo).use(store).use(plugins).use(directives)

  if (window.__POWERED_BY_QIANKUN__) {
    // 接入乾坤
    console.log(`[应用初始化[${props.name}]]`, props)

    switch (props.platform) {
      // 特资星
      case QIANKUN_PLATFORM.TZX: {
        break
      }

      default: {
        // 法诉平台
        app.use(router)
        enhanceRouter(router._router as any)

        // 在qiankun中通用
        const appMountDom = props.container.querySelector('#app')
        if (appMountDom) {
          // 为了修复 vxe-table 样式丢失的问题
          appMountDom.setAttribute('data-vxe-ui-theme', 'light')
          appMountDom.classList.add('theme--tzx')
        }

        const appStore = useAppStore()

        appStore.microAppProps = markRaw(props)

        const userStore = useUserStore()
        const menuStore = useMenuStore()
        userStore.token = props.hubSharedStore?.token
        userStore.userInfo = deepClone(props.hubSharedStore?.user)
        userStore.departTree = deepClone(props.hubSharedStore?.departTree)
        userStore.departTree.__hasLoaded__ = true
        const originMenusData = deepClone(props.hubSharedStore?.originMenusData)
        menuStore.menuData = menuStore.compatMenuData(originMenusData)

        console.log(
          'appStore',
          appStore,
          props.hubSharedStore?.user,
          props.hubSharedStore?.departTree,
          props.hubSharedStore?.originMenusData
        )

        const layoutStore = useLayoutStore()
        layoutStore.isHeaderShow = false
        layoutStore.isMenuShow = true

        appStore.router = router._router as any
        setup.__ROOT_VUE_INSTANCE__ = app

        menuStore._handleMenuData()

        app.mount(appMountDom)
        break
      }
    }
  } else {
    app.use(router)
    enhanceRouter(router._router as any)
    app.mount('#app')
    const appStore = useAppStore()
    appStore.router = router._router as any
    setup.__ROOT_VUE_INSTANCE__ = app
  }
  afterMount()
  return app
}

/**
 * 挂载之后执行
 */
function afterMount() {
  const appStore = useAppStore()
  to(appStore.getPublicIp())
}

if (!window.__POWERED_BY_QIANKUN__) {
  initApp()
}

/**
 * 开始
 * @return {Promise<void>}
 */
export async function bootstrap() {}

/**
 * 挂载
 * @param props
 * @return {Promise<unknown>}
 */
export async function mount(props) {
  try {
    initApp(props)
    console.log('挂载了', props)
  } catch (e) {
    console.error('[挂载失败了]', e)
  }
}

/**
 * 卸载
 */
export async function unmount() {
  if (app) {
    app.unmount()
    app._container.innerHTML = ''
    app = null
  }
}

async function task() {
  let __enableDevtool__ = await dbSimple.getItem('__enableDevtool__')
  console.log('window', window)
  Object.defineProperties(window, {
    __enableDevtool__: {
      get() {
        return __enableDevtool__
      },
      set(val) {
        __enableDevtool__ = val
        dbSimple.setItem('__enableDevtool__', val)
        return true
      }
    }
  })

  // 上报基调听云
  if (isPlainObject(profile.tingyun) && profile.IS_PRO && [`prd`, `uat`].includes(profile.APP_MODE)) {
    import('@tingyun-sdk/web').then(({ default: Tingyun }) => {
      Tingyun.init(profile.tingyun)

      // 本地
      setTimeout(() => {
        const userStore = useUserStore()
        watch(
          () => userStore.userInfo?.id,
          (newVal) => {
            newVal ? localStorage.setItem('TY_USER_ID', newVal) : localStorage.removeItem('TY_USER_ID')
          },
          {
            immediate: true
          }
        )
      }, 20)
    })
  }

  if (profile.IS_PRO) {
    const forbiddenDebug = [`uat`, `prd`].includes(profile.APP_MODE)
    if (forbiddenDebug) {
      console.warn(`当前环境禁止调试`)
      // 防止 debugger
      DisableDevtool({
        disableMenu: false,
        clearLog: true,
        url: undefined,
        ondevtoolopen() {
          eval('debugger;')
        },
        ignore: () => {
          return (window as any).__enableDevtool__ == true
        }
      })
    }

    // 是否允许自动更新 提示
    const canPolling = [`dev`, `sit`, `uat`].includes(profile.APP_MODE)
    if (canPolling) {
      // 更新版本
      updateAppVersionPolling({
        appETagKey: `__app_etag__${pkg.name}__${pkg.version}`
        // htmlFileUrl: `${origin}`
      })
    }
  }
}

task()
